package cn.samehope.pet;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * 基础SERVICE
 * @author LD
 *
 * @param <M>
 */
public class BaseService<M extends Model<M>>{

	public M dao;
	
	@SuppressWarnings("unchecked")
	public BaseService() {
        Class<M> modelClass = null;
        Type t = getUsefulClass(getClass()).getGenericSuperclass();
        //判断是否泛型参数化
        if (t instanceof ParameterizedType) {
            Type[] p = ((ParameterizedType) t).getActualTypeArguments();
            modelClass = (Class<M>) p[0];
        }

        try {
	        if (modelClass == null) {
	            throw new Exception("can not get parameterizedType in JbootServiceBase");
	        }

			dao = modelClass.newInstance().dao();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	public M getdao() {
        return dao;
    }


    /**
     * 根据ID查找model
     *
     * @param id
     * @return
     */
    public M findById(Object id) {
        return dao.findById(id);
    }


    /**
     * 查找全部数据
     *
     * @return
     */
    public List<M> findAll() {
    	String tableName = TableMapping.me().getTable(dao.getClass()).getName();
    	String sql = " select * from " + tableName;
        return dao.find(sql);
    }


    /**
     * 根据ID 删除model
     *
     * @param id
     * @return
     */
    public boolean deleteById(Object... idValues) {
        return dao.deleteById(idValues);
    }

    /**
     * 删除
     *
     * @param model
     * @return
     */
    public boolean delete(M model) {
        return model.delete();
    }


    /**
     * 保存到数据库
     *
     * @param model
     * @return
     */
    public boolean save(M model) {
        return model.save();
    }

    /**
     * 更新
     *
     * @param model
     * @return
     */
    public boolean update(M model) {
        return model.update();
    }
    
    /**
     * 分页查询
     * @param pageNumber
     * @param pageSize
     * @param select
     * @param sqlExceptSelect
     * @param paras
     * @return
     */
    public Page<M> paginate(int pageNumber, int pageSize, String select, String sqlExceptSelect, Object... paras){
    	return dao.paginate(pageNumber, pageSize, select, sqlExceptSelect, paras);
    }
    
    public static Class<?> getUsefulClass(Class<?> clazz) {
        //ControllerTest$ServiceTest$$EnhancerByGuice$$40471411#hello
        //com.demo.blog.Blog$$EnhancerByCGLIB$$69a17158
        return clazz.getName().indexOf("$$EnhancerBy") == -1 ? clazz : clazz.getSuperclass();
    }
}
